<template>
	<view class="container">
		<view class="payment-form">
			<view class="header">
				<text class="shop-name">{{ shopName }}</text>
				<text v-if="shop?.status === 'closed'" class="shop-status">已打烊</text>
			</view>
			<view class="form-item">
				<text class="label">付款金额</text>
				<view class="amount-input-container">
					<text class="currency-symbol">¥</text>
					<input 
						type="digit" 
						v-model="amount" 
						@input="validateAmount" 
						class="input" 
						placeholder="请输入付款金额" 
						:maxlength="moneyMaxLeng"
					/>
				</view>
				<text class="amount-tip" v-if="amount">{{ formatAmount }}</text>
			</view>
			<button @click="handlePayment()" class="payment-button" :disabled="!paymentable || !isValidAmount">
				立即支付 {{ amount ? `￥${amount}` : '' }}
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		computed,
		ref,
		watch
	} from "vue";
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import {
		getShopInfo
	} from "../../api/market";
	import {
		useMainStore
	} from "@/store/store";
	import {
		storeToRefs
	} from "pinia";
	import {
		createScanPaymentOrder
	} from "../../api/order";	import {
		userAuthSession,
		wechatAuth,
		alipayAuth
	} from '@/api/auth'
	import { ensurePlatformId } from '@/utils/platformId';
	import { getPlatform } from '@/utils/platform';
	const title = ref("扫码支付");
	const amount = ref("");
	const moneyMaxLeng = ref(8);
	const minAmount = 0.01;
	const maxAmount = 50000;
	const isValidAmount = computed(() => {
		const num = parseFloat(amount.value);
		return !isNaN(num) && num >= minAmount && num <= maxAmount;
	});

	const formatAmount = computed(() => {
		const num = parseFloat(amount.value);
		if (isNaN(num)) return '';
		if (num < minAmount) return `金额不能小于${minAmount}元`;
		if (num > maxAmount) return `金额不能大于${maxAmount}元`;
		return `￥${num.toFixed(2)}`;
	});

	const shop = ref();
	const shopId = ref("");
	const platform = getPlatform();
	const payType = ref(platform === 'alipay' ? 'alipay' : 'weixin');
	const paymentButtonCustomStyle = computed(() => {
		return {
			width: "80%",
		};
	});
	const paymentable = ref(true);

	const main = useMainStore();
	const {
		member,
		isLogin,
		openid,
		buyerId
	} = storeToRefs(main);
	// const onClickLeft = () => {
	// 	uni.navigateBack();
	// }

	const shopName = ref("示例店铺");
	const handlePayment = async () => {
		// 检查登录状态
		if (!isLogin.value) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}, 1500);
			return;
		}

		// 检查平台特定的用户ID
		if (platform === 'alipay' && !buyerId.value) {
			uni.showToast({
				title: '需要支付宝授权',
				icon: 'none'
			});
			alipayMiniLogin();
			return;
		} else if (platform !== 'alipay' && !openid.value) {
			uni.showToast({
				title: '需要微信授权',
				icon: 'none'
			});
			wechatMiniLogin();
			return;
		}

		// 确保平台ID存在
		const hasPlatformId = await ensurePlatformId('payment');
		if (!hasPlatformId) {
			uni.showToast({
				title: '需要授权后才能支付',
				icon: 'none'
			});
			return;
		}
		
		if (!shop.value) {
			uni.showToast({
				title: "店铺信息不存在",
				icon: "none",
			});
			return;
		}

		if (shop.value.status === 'closed') {
			uni.showToast({
				title: "店铺已打烊，暂不能支付",
				icon: "none",
			});
			return;
		}

		if (!isValidAmount.value) {
			uni.showToast({
				title: `支付金额必须在${minAmount}~${maxAmount}元之间`,
				icon: "none",
			});
			return;
		}

		// 支付确认
		try {
			const [err, confirmRes] = await uni.showModal({
				title: '确认支付',
				content: `确认向 ${shopName.value} 支付 ¥${amount.value} 吗？`,
				confirmText: '确认支付',
				cancelText: '取消'
			});
			
			if (err || !confirmRes.confirm) return;
			
			// 支付请求中
			uni.showLoading({
				title: "支付请求中",
			});

			paymentable.value = false;

			// 设置支付超时
			const paymentTimeout = setTimeout(() => {
				uni.hideLoading();
				uni.showToast({
					title: '支付超时，请重试',
					icon: 'none'
				});
				paymentable.value = true;
			}, 30000); // 30秒超时

			let from = platform === 'alipay' ? 'alipay' : 'routine';
			let data = {
				openid: platform === 'alipay' ? '' : openid.value,
				buyerId: platform === 'alipay' ? buyerId.value : '',
				orderType: "scan_payment",
				shopId: shop.value.id,
				payType: payType.value,
				form: from,
				amount: amount.value || 0,
			};

			let result = await createScanPaymentOrder(data);
			clearTimeout(paymentTimeout);

			if (!result) {
				uni.hideLoading();
				uni.showToast({
					title: '创建订单失败',
					icon: 'none'
				});
				paymentable.value = true;
				return;
			}

			// 页面跳转到结算页
			if (result.code === 0 && result.data && result.data.orderId) {
				uni.hideLoading();
				uni.navigateTo({
					url: `/pages/order/checkout?orderId=${result.data.orderId}`
				});
			} else {
				uni.hideLoading();
				uni.showToast({
					title: result.message || '支付失败，请重试',
					icon: 'none'
				});
				paymentable.value = true;
			}
		} catch (error) {
			console.error('支付错误:', error);
			uni.hideLoading();
			uni.showToast({
				title: '支付异常，请重试',
				icon: 'none'
			});
			paymentable.value = true;
		}
	};

	const wechatMiniLogin = async () => {
		try {
			uni.showLoading({
				title: '登录中'
			});

			const [loginErr, loginRes] = await uni.login({
				provider: 'weixin'
			});

			if (loginErr) {
				throw new Error('微信登录失败');
			}

			const data = await userAuthSession({
				code: loginRes.code
			});

			if (!data) {
				throw new Error('获取用户信息失败');
			}

			main.SET_OPENID(data.openId);

			if (data.hasOwnProperty('userInfo') && data.accessToken && data.accessToken !== '') {
				main.SET_MEMBER(data.userInfo);
				main.SET_TOKEN(data.accessToken);
				main.SET_ACCESSES(data.accesses);
			}

			uni.hideLoading();
		} catch (error) {
			console.error('登录错误:', error);
			uni.hideLoading();
			uni.showToast({
				title: error.message || '登录失败，请重试',
				icon: 'none'
			});

			// 3秒后重试
			setTimeout(() => {
				wechatMiniLogin();
			}, 3000);
		}
	}

	const alipayMiniLogin = async () => {
		try {
			uni.showLoading({
				title: '登录中'
			});

			// 获取支付宝授权码
			const [authErr, authRes] = await uni.getAuthCode({
				scopes: 'auth_base'
			});

			if (authErr) {
				throw new Error('支付宝授权失败');
			}

			// 使用授权码获取用户信息
			const data = await alipayAuth({
				authCode: authRes.authCode
			});

			if (!data) {
				throw new Error('获取用户信息失败');
			}

			// 设置支付宝用户ID
			if (data.buyerId) {
				main.SET_BUYER_ID(data.buyerId);
			}

			if (data.hasOwnProperty('userInfo') && data.accessToken && data.accessToken !== '') {
				main.SET_MEMBER(data.userInfo);
				main.SET_TOKEN(data.accessToken);
				main.SET_ACCESSES(data.accesses);
			}

			uni.hideLoading();
		} catch (error) {
			console.error('支付宝登录错误:', error);
			uni.hideLoading();
			uni.showToast({
				title: error.message || '登录失败，请重试',
				icon: 'none'
			});

			// 3秒后重试
			setTimeout(() => {
				alipayMiniLogin();
			}, 3000);
		}
	}

	const handleLogin = () => {
		if (platform === 'alipay') {
			if (!buyerId.value) {
				alipayMiniLogin();
			}
		} else {
			if (!openid.value) {
				wechatMiniLogin();
			}
		}
	}

	onShow(() => {
		console.log("init");

		handleLogin();

		if (shopId.value) {
			console.log("shopId =>>", shopId.value);
			loadShopInfo(shopId.value).then((result) => {
				console.log(result);
			});
		}
		paymentable.value = true;
		console.log(paymentable.value);


	});



	onLoad((options) => {
		//没从当前url 获取 参数 shopId 的值
		// 通过uni.getStorageSync('shopId') 获取

		console.log("options=>>>>", options);

		// 扫码截取参数
		if (options.q !== undefined) {
			let q = decodeURIComponent(options.q);
			try {
				// 使用 URL 对象解析参数
				const url = new URL(q);
				const params = new URLSearchParams(url.search);
				const shopIdParam = params.get('shopId');
				
				if (!shopIdParam) {
					throw new Error('无效的店铺二维码');
				}
				
				shopId.value = shopIdParam;
			} catch (error) {
				console.error('解析二维码参数错误:', error);
				uni.showToast({
					title: '无效的店铺二维码',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		}

		paymentable.value = true;
		console.log(paymentable.value);
	});

	const loadShopInfo = async (shopId) => {
		try {
			uni.showLoading({
				title: '加载店铺信息'
			});
			
			const shopInfo = await getShopInfo({
				shopId: shopId,
			});
			
			uni.hideLoading();
			
			if (!shopInfo) {
				uni.showToast({
					title: '店铺信息加载失败',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
				return;
			}
			
			shop.value = shopInfo;
			title.value = shopInfo.name;
			shopName.value = shopInfo.name || "示例店铺";
			
			// 检查店铺状态
			if (shopInfo.status === 'closed') {
				uni.showToast({
					title: '店铺已打烊',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('加载店铺信息错误:', error);
			uni.hideLoading();
			uni.showToast({
				title: '网络错误，请重试',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
	};

	const validateAmount = () => {
		let val = amount.value.toString();
		val = val.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
		val = val.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
		val = val.replace(/^0+\./g, "0.");
		val = val.match(/^0+[1-9]+/) ? (val = val.replace(/^0+/g, "")) : val;
		val = val.match(/^\d*(\.?\d{0,2})/g)[0] || "";

		if (val.includes(".")) {
			let numDianValue = val.toString().split(".")[1];
			let numDian = numDianValue.length;
			if (numDian === 2) {
				moneyMaxLeng.value = val.length;
			}
			if (numDianValue.length > 2) {
				numDianValue = numDianValue.substring(0, 2);
				val = val.toString().split(".")[0] + "." + numDianValue;
			}
		} else {
			moneyMaxLeng.value = 8;
		}
		amount.value = val;
	};
</script>

<style>
	.container {
		padding: 20px;
	}

	.payment-form {
		margin-top: 50px;
		background-color: #ffffff;
		border-radius: 10px;
		padding: 20px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.header {
		/* background-color: #07c160; */
		padding: 20px;
		text-align: center;
	}

	.form-item {
		margin-bottom: 20px;
	}

	.label {
		display: block;
		margin-bottom: 5px;
		font-size: 14px;
		color: #333;
	}

	.amount-input-container {
		position: relative;
		display: flex;
		align-items: center;
		width: 100%;
		height: 50px;
		border: 1px solid #dcdfe6;
		border-radius: 4px;
		padding: 0 15px;
	}

	.currency-symbol {
		font-size: 20px;
		color: #333;
		margin-right: 5px;
	}

	.input {
		flex: 1;
		height: 100%;
		border: none;
		font-size: 20px;
	}

	.amount-tip {
		font-size: 12px;
		color: #999;
		margin-top: 5px;
	}

	.shop-status {
		font-size: 12px;
		color: #ff4d4f;
		margin-left: 10px;
	}

	.payment-button {
		width: 100%;
		height: 44px;
		background-color: #007aff;
		color: #ffffff;
		border: none;
		border-radius: 4px;
		font-size: 16px;
	}

	.payment-button[disabled] {
		background-color: #cccccc;
		cursor: not-allowed;
	}
</style>